<template>
    <el-container class="container">
        <el-header class="header">
            <el-menu mode="horizontal" :ellipsis="false" @select="" @open="" @close="" router>
                <el-menu-item index="/tenant/maintenant">
                    <el-icon>
                        <OfficeBuilding />
                    </el-icon>
                    高新物业系统-租户端
                </el-menu-item>
                <el-text class="welcome-text">
                    {{ greeting }}
                </el-text>


                <!-- 控制后续组件靠右 -->
                <div class="flex-grow" />

                <el-sub-menu index="0">
                    <template #title>
                        <el-icon>
                            <Avatar />
                        </el-icon>
                        账号设置
                    </template>
                    <el-menu-item index="">
                        <div @click="userCenterDialog = true">
                            <el-icon>
                                <Menu />
                            </el-icon>
                            个人信息
                        </div>
                    </el-menu-item>

                    <el-menu-item index="">
                        <div @click="updatePwdDialog = true">
                            <el-icon>
                                <Tools />
                            </el-icon>
                            修改密码
                        </div>
                    </el-menu-item>

                    <el-menu-item index="">
                        <div @click="logoutDialog = true">
                            <el-icon>
                                <SwitchButton />
                            </el-icon>
                            退出登录
                        </div>
                    </el-menu-item>
                </el-sub-menu>
            </el-menu>
        </el-header>

        <el-container>
            <el-main class="main">
                <RouterView />
            </el-main>
            <el-divider direction="vertical"></el-divider>

            <el-aside class="right-messageview"><br>
                <el-scrollbar height="800px">
                    <el-text size="large" tag="b">我的消息：{{ messageNumber }} 条</el-text><br><br>

                    <div v-if="messageNumber == 0">
                        <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                        <el-text size="large">--暂无消息--</el-text>
                    </div>

                    <div v-if="messageNumber > 0">
                        <div v-for="message in messageData" :key="message.id">
                            <el-text tag="b">
                                <el-icon>
                                    <ChatDotSquare />
                                </el-icon>
                                {{ message.title }} &nbsp;
                            </el-text>
                            <el-text type="info" size="small">
                                {{ message.createTime }}
                            </el-text><br>
                            <el-text line-clamp="2" style="margin: 10px 0 18px 0;" type="info">
                                {{ message.content }}
                            </el-text>
                        </div>

                        <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                        <el-text size="large">---最多查看近30天消息---</el-text>
                    </div>

                </el-scrollbar>
            </el-aside>
        </el-container>
    </el-container>

    <el-dialog v-model="logoutDialog" title="退出登录" width="30%">
        <span>确认要退出登录吗？</span>

        <template #footer>
            <div class="dialog-footer">
                <el-button @click="logoutDialog = false">取消</el-button>
                <el-button type="primary" @click="logoutDialog = false; logout()">确认</el-button>
            </div>
        </template>
    </el-dialog>

    <el-dialog v-model="userCenterDialog" title="员工信息" width="35%">
        <el-row>
            <el-col :span="4">编号:</el-col>
            <el-col :span="20">{{ userInfo.id }}</el-col>
        </el-row> <br>
        <el-row>
            <el-col :span="4">姓名:</el-col>
            <el-col :span="20">{{ userInfo.name }}</el-col>
        </el-row> <br>
        <el-row>
            <el-col :span="4">电话:</el-col>
            <el-col :span="20">{{ userInfo.phone }}</el-col>
        </el-row> <br>
        <el-row>
            <el-col :span="4">性别:</el-col>
            <el-col :span="20">{{ userInfo.gender == 1 ? "男" : userInfo.gender == 0 ? "女" : "未填写" }}</el-col>
        </el-row> <br>
        <el-row>
            <el-col :span="4">邮箱:</el-col>
            <el-col :span="20">{{ userInfo.email }}</el-col>
        </el-row> <br>
        <el-row>
            <el-col :span="4">地址:</el-col>
            <el-col :span="20">{{ userInfo.address }}</el-col>
        </el-row> <br>

        <el-divider></el-divider>
        <el-button type="primary" round plain @click="updatePwdDialog = true;">修改密码</el-button>
    </el-dialog>

    <el-dialog v-model="updatePwdDialog" title="修改密码" width="34%">
        <el-row>
            <el-col :span="7">请输入原密码：</el-col>
            <el-col :span="16"><el-input v-model="oldPwd" placeholder="请输入原密码" show-password clearable /></el-col>
        </el-row>
        <br>
        <el-row>
            <el-col :span="7">请输入新密码：</el-col>
            <el-col :span="16"><el-input v-model="newPwd" placeholder="请输入新密码" show-password clearable /></el-col>
        </el-row>

        <template #footer>
            <div class="dialog-footer">
                <el-button @click="updatePwdDialog = false">取消</el-button>
                <el-button type="primary" @click="updatePwd">确认</el-button>
            </div>
        </template>
    </el-dialog>

</template>

<script setup>
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import { useRouter } from "vue-router";
let router = useRouter();

import { useUserInfoStore } from '@/stores/userInfo.js';
const userInfoStore = useUserInfoStore();
const userInfo = userInfoStore.userInfo;

import { messageGetService } from '@/api/other.js';
import { userLogoutService, userUpdatePwdService } from '@/api/user';

//默认展示数据总览页面
router.push("/tenant/maintenant");

let logoutDialog = ref(false);
let userCenterDialog = ref(false);
let updatePwdDialog = ref(false);

let oldPwd = ref('');
let newPwd = ref('');

let greeting = '';
let name = userInfo.name
let gender = userInfo.gender
if (gender == 1) {
    name = name + " 先生~"
} else if (gender == 0) {
    name = name + " 女士~"
} else {
    name = name + " 先生/女士 ~"
}

// 根据时间段显示不同问候语
const greet = () => {
    const now = new Date();
    const hour = now.getHours();

    if (hour >= 4 && hour < 8) {
        greeting = '早上好，' + name;
    } else if (hour >= 8 && hour < 11) {
        greeting = '上午好，' + name;
    }
    else if (hour >= 11 && hour < 14) {
        greeting = '中午好，' + name;
    }
    else if (hour >= 14 && hour < 18) {
        greeting = '下午好，' + name;
    } else {
        greeting = '晚上好，' + name;
    }

    setTimeout(greet, 1000 * 60 * 10);
}
greet();

//获取消息列表
async function getMessage() {
    try {
        let result = await messageGetService(3, userInfo.id)
        if (result.code == 200) {
            messageData.value = result.data.list
            messageNumber.value = result.data.total
        }
        else if (result.code == 401) {
            ElMessage.error(result.msg)
            router.push({ path: '/login' });
        } else {
            ElMessage.warning(result.msg)
        }
    } catch (error) {
        ElMessage.error('系统异常 (getMessage)')
    }
}

async function logout() {
    try {
        let result = await userLogoutService(userInfo.id)
        if (result.code == 200) {
            // 服务端登录信息已清除
            // 对前端登录信息进行清除
            userInfoStore.removeUserInfo()
            ElMessage.info(result.msg)
            router.push({ path: '/login' });
        } else {
            ElMessage.error(result.msg)
        }
    } catch (error) {
        ElMessage.error('系统异常 (logout)')
    }
}

async function updatePwd() {
    try {
        let result = await userUpdatePwdService(userInfo.identity, userInfo.id, oldPwd.value, newPwd.value)
        if (result.code == 200) {
            ElMessage.success(result.msg)
            userInfoStore.removeUserInfo()
            router.push({ path: '/login' });
        } else {
            ElMessage.warning(result.msg)
        }
    } catch (error) {
        ElMessage.error('系统异常 (updatePwd)')
    }
}


// WebSocket
console.log('currentUser:' + userInfo.id + '  ' + userInfo.identity)
let socket = new WebSocket('ws://localhost:8081/websocket/' + userInfo.id);
let messageData = ref([{ id: '', title: null, createTime: null, content: null }])
let messageNumber = ref(0)
const connect = () => {
    socket.onopen = () => {
        console.log('WebSocket connection established.');
    };

    socket.onmessage = (event) => {
        ElMessage.success(event.data)
        getMessage()
    };

    socket.onerror = (error) => {
        console.error('WebSocket error:', error);
    };

    socket.onclose = (event) => {
        console.log('WebSocket connection closed. Reason:' + event.reason);
        // 可以写一些重连之类的逻辑，但我不会写，哈哈
    };
};
connect();

</script>

<style>
.flex-grow {
    flex-grow: 1;
}

.welcome-text {
    margin-left: 100px;
}

.el-divider--vertical {
    height: 40em;
}
</style>